package com.gitee.slowcreator.http.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Map;

/**
 * @author zxw
 * @date 2023/1/6 下午10:32
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class UrlUtil {

    private static final String PARAMS_BEGIN = "?";

    private static final String PARAM_SEPARATE = "&";
    private static final String PARAM_EQUAL = "=";


    public static String rebuildUrl(String url, Map<String, String[]> httpParams) {

        if (StrUtil.isBlank(url)) {
            throw new IllegalArgumentException("url不能为空！");
        }

        if (CollectionUtil.isEmpty(httpParams)) {
            return url;
        }

        StrBuilder urlBuild = new StrBuilder(url);
        if (!StrUtil.contains(url, PARAMS_BEGIN)) {
            urlBuild.append(PARAMS_BEGIN)
                    .append("_r=1");
        }

        for (Map.Entry<String, String[]> entry : httpParams.entrySet()) {

            String key = entry.getKey();
            String[] value = entry.getValue();
            if (StrUtil.isBlank(key) || ArrayUtil.isEmpty(value)) {
                continue;
            }
            for (String v : value) {
                urlBuild.append(PARAM_SEPARATE)
                        .append(key)
                        .append(PARAM_EQUAL)
                        .append(v);
            }

        }

        return urlBuild.toString(true);
    }
}
